import os
import shutil
import subprocess

def build_executable():
    """使用PyInstaller打包Flask应用为可执行文件"""
    
    # 清理之前的构建文件
    clean_build_files()
    
    # 创建spec文件内容
    spec_content = '''
# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(['app.py'],
             pathex=['.'],
             binaries=[],
             datas=[('templates', 'templates'), ('static', 'static'), ('video_list.json', '.')],
             hiddenimports=['flask', 'webbrowser', 'threading', 'json', 'os'],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='SmartAgriSystem',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=True,
          disable_windowed_traceback=False,
          target_arch=None,
          codesign_identity=None,
          entitlements_file=None )

coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               upx_exclude=[],
               name='SmartAgriSystem')
'''
    
    # 写入spec文件
    with open('SmartAgriSystem.spec', 'w') as f:
        f.write(spec_content)
    
    # 运行PyInstaller
    try:
        subprocess.run(['pyinstaller', 'SmartAgriSystem.spec', '--clean'], check=True)
        print("打包成功！可执行文件在dist/SmartAgriSystem目录下")
        
        # 复制视频文件夹到dist目录
        copy_video_folder()
        
    except subprocess.CalledProcessError as e:
        print(f"打包失败: {e}")
    except Exception as e:
        print(f"打包过程中出现错误: {e}")

def clean_build_files():
    """清理构建的构建文件"""
    folders_to_clean = ['build', 'dist', '___cache']
    
    for folder in folders_to_clean:
        if os.path.exists(folder):
            try:
                shutil.rmtree(folder)
                print(f"清理文件夹: {folder}")
            except Exception as e:
                print(f"清理文件夹 {folder} 时出错: {e}")
    
    # 清理spec文件
    if os.path.exists('SmartAgriSystem.spec'):
        try:
            os.remove('SmartAgriSystem.spec')
            print("清理spec文件")
        except Exception as e:
            print(f"清理spec文件时出错: {e}")

def copy_video_folder():
    """复制视频文件夹到dist目录"""
    source = 'static/smart-agri-videos'
    destination = 'dist/SmartAgriSystem/static/smart-agri-videos'
    
    try:
        if os.path.exists(source):
            if os.path.exists(destination):
                shutil.rmtree(destination)
            shutil.copytree(source, destination)
            print(f"复制视频文件夹到: {destination}")
        else:
            print(f"视频文件夹 {source} 不存在，跳过复制")
    except Exception as e:
        print(f"复制视频文件夹时出错: {e}")

if __name__ == '__main__':
    build_executable()
